// pages/index/wode/bind_phone/bind_phone.js
import ajax from "../../../../utils/ajax.js";
let app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',
    msg_code:'',
    can_confirm:true,
    msg_btn_text:'获取验证码',
    can_msg_btn:true
  },
  input_phone(e){
    this.setData({
      phone:e.detail.value
    })
    this.is_can_confirm()
  },
  input_msg_code(e){
    this.setData({
      msg_code:e.detail.value
    })
    this.is_can_confirm()

  },
  is_can_confirm(){
    if(this.data.phone&&this.data.msg_code){
      this.setData({
        can_confirm:false
      })
    }else{
      this.setData({
        can_confirm:true
      })
    }
  },
  confirm_msg(){
    ajax.post({
      url:'user/bind_mobile',
      data:{
        mobile:this.data.phone,
        code:this.data.msg_code
      }
    }).then(res=>{
      console.log(res);
      if(res.code==0){
        app.toast("绑定成功");
        // 更新缓存中的 用户数据
        app.common.user_info.mobile = this.data.phone;
        let user_info = wx.getStorageSync('user_info');
        user_info.mobile = this.data.phone;
        wx.setStorageSync('user_info', user_info);
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1000);
      }
    })
  },
  get_msg_code(){
    console.log("get_msg_code");
    let phone = this.data.phone;
    if(phone.length!=11){
      app.toast("请输入正确的手机号");
      return
    }
   
    ajax.get({
      url:'send_sms',
      data:{
        type:'bind_mobile',
        mobile:phone
      }
    }).then(res=>{
      console.log(res);
      if(res.code==0){
        let sec = 60;
        this.setData({
          can_msg_btn:false
        })
        let timer = setInterval(()=>{
          this.setData({
            msg_btn_text:'重新获取'+sec
          })
          if(sec==0){
            this.setData({
              can_msg_btn:true,
              msg_btn_text:'获取验证码'
            });
            clearInterval(timer)
          }
          sec--;
        },1000)
        
        app.toast("发送成功");
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onShow(){
    this.is_can_confirm()
  }

})